package com.example.docmanagement.repository;

import com.example.docmanagement.dto.response.CustomerResponse;
import com.example.docmanagement.entity.Customer;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {

        /**
         * 根据状态查询客户
         * 使用构造函数表达式直接返回 DTO，避免 N+1 查询问题
         * 
         * @param status   客户状态（可选）
         * @param pageable 分页参数
         * @return 分页的客户响应列表
         */
        @Query("SELECT new com.example.docmanagement.dto.response.CustomerResponse(" +
                        "d.id, d.name, d.email, d.phone, d.status, " +
                        "d.createdAt, u1.id, u1.username, d.updatedAt, u2.id, u2.username) " +
                        "FROM Customer d " +
                        "LEFT JOIN d.createdByUser u1 " + // 使用实体关联，避免 N+1 查询
                        "LEFT JOIN d.updatedByUser u2 " + // 使用实体关联，避免 N+1 查询
                        "WHERE (:status IS NULL OR d.status = :status) " +
                        "ORDER BY d.updatedAt DESC")
        Page<CustomerResponse> searchCustomersWithStatus(
                        @Param("status") String status, Pageable pageable);

        /**
         * 根据名称判断客户是否存在
         */
        boolean existsByName(String name);
}
